// components/classtable/class-table.js
const app = getApp()
const db = wx.cloud.database()
var sev = require('../../utils/sev.js');
var md5 = require('../../utils/md5.js');
var color = ["#85B8CF", "#90C652", "#D8AA5A", "#FC9F9D", "#0A9A84", "#61BC69", "#12AEF3", "#E29AAD", "#CDC9C9", "#6A5ACD", "#836FFF"];
var colorN = color.length;
Component({
  /**
   * 组件的属性列表
   */
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    showdata:null,
    edclass: [],
    xnxqid: '',
    touchx: '',
    touchy: '',
    zc:'',
    edudata:null,    
    token:'',
   // tmpclass:[],//临时数据表
    storgeclass: [],//缓存课程
    modalName:null,
    beginzc:'',//开始时间
    endzc:'',//结束时间
    today:'',//周几
    classindex:'',//第几节课
   
    tmpobj:'',//临时课程数据
    kcsj:'',//课程时间
    kcmc:'',//课程名称
    jsmc:'',//教室名称
    todeal:true
    
  },
  /**
   * 组件的生命周期 
   */
  lifetimes:{
    
    created(){
      var that = this;
      console.log('created!')
      //时间查询
      //console.log(sev.getTime())
      wx.showLoading({
        title: '请求课表数据中',
      })
      wx.cloud.callFunction({name:'sync',data:{URL:sev.getTime(),token:app.eduOS.token},success(res){console.log(res)
      //回调函数,稳定顺序
      that.setData({
        xnxqid:res.result.xnxqh,
        zc:8,
        beginzc:res.result.zc
      }, () => { 
        //that.RequestData();
        //根据周次删选出来需要初始化的自定义课表
        //需要延时函数? 把这两个分开渲染怎么样?
      
        wx.getStorage({
          key: 'editclass',
          success: function(ans) {
            //console.log(ans.data);
            var cklist = [];
            for(var i = 0 , len = ans.data.length;i<len;i++){
              if(that.data.zc>=ans.data[i].beginzc&&that.data.zc<=ans.data[i].endzc){
                cklist.push(ans.data[i]);
              }
            };
           // console.log(ans.data);
            var timeout = setTimeout(function(){
              
              that.setData({ edclass: cklist ,storgeclass:ans.data}, () => {
                //console.log(that.data.storgeclass)
                clearTimeout(timeout);
                that.RequestData();
              })
            },1000);
            
          },fail(){
            that.RequestData();
          }
        })
        })
      }});
      wx.getStorage({
        key: 'educookie',
        success: function(res) {
          console.log(res);
          that.setData({
            edudata:res.data
          })
        },
      });
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    
    sureedit(){
      
      var that = this;
      //console.log(this.data.storgeclass);
      //console.log(this.data.tmpclass);
      var obj = {
        "jsmc":that.data.jsmc,
        "kcsj":that.data.kcsj,
        "kcmc":that.data.kcmc,
        "beginzc":that.data.beginzc,
        "endzc":that.data.endzc
      };
     // console.log();
      wx.setStorage({
        key: 'editclass',
        data: that.data.storgeclass.concat([obj]) ,
        success(res){
          console.log(res)
        }
      })
     // console.log(obj);
      that.hideModal();
    },
    //获取模态内容
    getkcmc(e) { this.setData({ kcmc: e.detail.value }) },
    getjsmc(e) { this.setData({ jsmc: e.detail.value }) },
    getbeginzc(e) { this.setData({ beginzc: e.detail.value }) },
    getendzc(e) { this.setData({ endzc: e.detail.value }) },
    touchStart(e) {
      var that = this;
      that.setData({
        touchx: e.changedTouches[0].clientX,
        touchy: e.changedTouches[0].clientY
      })
    },
    touchEnd(e) {
      var that = this;
      let x = e.changedTouches[0].clientX;
      let y = e.changedTouches[0].clientY;
      let turn = "";
      if (x - that.data.touchx > 50 && Math.abs(y - that.data.touchy) < 50) {      //右滑
        turn = "right";
      } else if (x - that.data.touchx < -50 && Math.abs(y - that.data.touchy) < 50) {   //左滑
        turn = "left";
      }
      if (turn == 'left' && this.data.zc<=28) {
        var cklist = [];
        //that.setData({edclass:[]});
        wx.showLoading({
          title: '加载下周',
        })
        that.setData({
         // edclass:that.data.tmpclass,
          zc: that.data.zc + 1,
          beginzc: that.data.zc + 1
        },()=>{
          
          var tmplist = that.data.storgeclass;
          //console.log(tmplist);
          for(var i= 0,len = tmplist.length;i<len;i++){
            if (that.data.zc >= tmplist[i].beginzc && that.data.zc <= tmplist[i].endzc) {
              cklist.push(tmplist[i]);
            }
          };
          var timeout = setTimeout(function(){
            that.setData({edclass:cklist},()=>{
              clearTimeout(timeout);
              that.RequestData()
            })
            
          },1000);
          });
          
      } else if (turn == 'right' && this.data.zc>1) {
        var cklist = [];
        //that.setData({ edclass: [] });
        wx.showLoading({
          title: '加载上周',
        })
        that.setData({
         // edclass: that.data.tmpclass,
          zc:that.data.zc - 1,
          beginzc: that.data.zc - 1
        }, () => {
          
          var tmplist = that.data.storgeclass;
          for (var i = 0, len = tmplist.length; i < len; i++) {
            if (that.data.zc >= tmplist[i].beginzc && that.data.zc <= tmplist[i].endzc) {
              cklist.push(tmplist[i]);
            }
          };
          var timeout = setTimeout(function () {
            that.setData({ edclass: cklist }, () => {
              console.log(cklist);
              clearTimeout(timeout);
              that.RequestData()
            })

          }, 1000); });
      }
    },
    RequestData(){
      var that= this;
      //console.log(that.data.edclass);
      //console.log(sev.eduClass(this.data.xh,this.data.))
      wx.cloud.callFunction({ name: 'sync', data: { URL: sev.eduClass(this.data.edudata.xh, this.data.xnxqid, this.data.zc) ,token:app.eduOS.token},success(res){
        console.log(res);
       // wx.hideLoading();
      
        that.setData({
          edclass:that.data.edclass.concat(res.result)
        },()=>{
          that.dealClassTable();
          
        })
      }})
    },
    showModal(e) {
      this.setData({
        showdata: e.currentTarget.dataset.name,
        modalName: e.currentTarget.dataset.target
      })
    },
    hideModal(e) {
      this.setData({
        modalName: null
      })
    },
    dealClassTable() {
      var that = this;
      var list = that.data.edclass;
      if(list.length <= 1){
        wx.showModal({
          title: '没课了',
          content: '',
          showCancel:false,
          success:function(res){
            if(res.confirm){
              wx.navigateBack({
                
              })
            }
          }
        })
        wx.hideLoading()
      }
      //wx.hideLoading();
      //console.log(list);
      list.map(function (value, index) {
        // value.top = ((parseInt(value.kcsj.substring(1, 3)) - 1) * 68) + 'px';
        // value.height = ((parseInt(value.kcsj.substring(3, 5)) - parseInt(value.kcsj.substring(1, 3))) * 130) + 'px';

        value.height = "calc(100% / 5 - 8px)";

        value.color = color[md5.hexMD5(value.kcmc)[0].charCodeAt() % colorN];
        value.top = "calc(100% / 5 * " + ((parseInt(value.kcsj.substring(1, 3)) - 1) / 2) + " + 2px )";

        value.left = 'calc(100% / 7 * ' + (parseInt(value.kcsj[0]) - 1) + " + " + (parseInt(value.kcsj[0]) * 3) + 'px)';

        return value;

      })
      that.setData({
        edclass:list
      },()=>{wx.hideLoading()
    //  console.log(list.length)
        wx.setStorage({
          key: 'stoclass' + that.data.zc,
          data: list
        })
      })
    },
    detail(e){
     // console.log(e)
      this.showModal(e);
      //this.showModal()
      //模态显示所有信息
    },
    toeditclass(e){
      var that = this;
      //console.log(e)
      // x/60 y/70 先预初始化时间
      var todayList = ['周一','周二','周三','周四','周五','周六','周天'];
      var classes = ['1~2节','3~4节','5~6节','7~8节','9~10节'];
      var classvalue = ['0102','0304','0506','0708','0910'];
      wx.showModal({
        title: 'Edit',
        content: '自定义课表',
        success(res){
          if(res.confirm){
            var x = e.detail.x;
            var y = e.detail.y;
            //console.log(x);
            var index_x = parseInt(x / 60);
            var index_y = parseInt(y / 140);
            console.log(todayList[index_x]);
            console.log(classes[index_y]);
            //console.log();
            that.setData({
              today:todayList[index_x],
              classindex:classes[index_y],
              modalName:'edit',
              kcsj: (index_x+1).toString() + classvalue[index_y]
            })
          }
        }
      })
    }
  }
})
